<template>
  <!-- 最外层的容器 -->
  <view class="my-settle-container">
    <!-- 全选区域 -->
    <label class="radio" @click="changeState">
      <radio color="#C00000" :checked="ifFullCheck" />
      <text>全选</text>
    </label>
    <!-- 合计区域 -->
    <view class="amount-box">
      合计:
      <text class="amount">￥{{ checkedAmount }}</text>
    </view>
    <!-- 结算按钮 -->
    <view class="btn-settle" @click="settlement">结算({{ checkedCount }})</view>
  </view>
</template>
<script>
import { mapGetters, mapMutations, mapState } from 'vuex';
export default {
  name: 'my-settle',
  data() {
    return {
      second: 3,
      timer: null
    };
  },
  methods: {
    ...mapMutations('m_cart', ['updateAllGoodsState']),
    ...mapMutations('m_user', ['updateRedirectInfo']),
    changeState() {
      // 遍历cart数组 把每个商品的状态都翻转一下
      this.updateAllGoodsState(!this.ifFullCheck);
    },
    settlement() {
      // 点击了结算
      // 判断是否有勾选的商品
      if (!this.checkedCount) return uni.$showMsg('请选择需要结算的商品');
      // 判断用户是否选择了收货地址
      if (!this.addstr) return uni.$showMsg('请选择收货地址');
      // 判断用户是否登录 如果没有登录，则三秒钟之后自动跳转到登录页面
      if (!this.token) return this.delayJump();
      // 结算的逻辑（支付）：
      this.payOrder();
    },
    // 结算的逻辑（支付）：
    async payOrder() {
      // 1,创建订单
      const orderInfo = {
        order_price: 0.01,
        consignee_addr: this.addstr,
        goods: this.cart
          .filter(item => item.goods_state)
          .map(x => ({
            goods_id: x.goods_id,
            goods_number: x.goods_count,
            goods_price: x.goods_price
          }))
      };
      const { data: res } = await uni.$http.post(
        '/api/public/v1/my/orders/create',
        orderInfo
      );
      if (res.meta.status !== 200) return uni.$showMsg('创建订单失败！');
      // 得到服务器响应的“订单编号”
      const orderNumber = res.message.order_number;
      // console.log(orderNumber);
      // 2,订单预支付
      const { data: res1 } = await uni.$http.post(
        '/api/public/v1/my/orders/req_unifiedorder',
        {
          order_number: orderNumber
        }
      );
      if (res1.meta.status !== 200) return uni.$showMsg('预付订单生成失败！');
      // console.log(res1.message.pay);
      const payInfo = res1.message.pay;

      // 3,发起微信支付
      const [err, succ] = await uni.requestPayment(payInfo);
      // console.log(res3);
      if (err) return uni.$showMsg('订单未支付');
      // 支付完成之后，想后端接口发起请求，查询支付结果
      const { data: res2 } = await uni.$http.post(
        '/api/public/v1/my/orders/chkOrder',
        {
          order_number: orderNumber
        }
      );
      if (res2.meta.status !== 200) return uni.$showMsg('订单未支付！');
      // 已经完成支付：
      uni.showToast({
        title: '支付完成'
      });
    },
    showCountDown() {
      uni.showToast({
        title: '请登录后再结算！' + this.second + '秒后自动跳转到登录页',
        icon: 'none',
        mask: true
      });
    },
    delayJump() {
      // 把秒设置为3
      this.second = 3;
      // 三秒钟之后自动跳转到登录页面
      this.showCountDown();
      this.timer = setInterval(() => {
        this.second--;
        if (this.second <= 0) {
          // 清理定时器
          clearInterval(this.timer);
          // 跳转到登录页
          uni.switchTab({
            url: '/pages/my/my',
            success: () => {
              // 把购物车页面的信息（要返回也能的信息）存到vuex中
              this.updateRedirectInfo({
                openType: 'switchTab',
                from: '/pages/cart/cart'
              });
            }
          });
          return;
        }
        this.showCountDown();
      }, 1000);
    }
  },
  computed: {
    ...mapGetters('m_cart', ['checkedCount', 'total', 'checkedAmount']),
    ...mapGetters('m_user', ['addstr']),
    ...mapState('m_user', ['token', 'redirectInfo']),
    ...mapState('m_cart', ['cart']),
    ifFullCheck() {
      return this.checkedCount === this.total;
    }
  }
};
</script>

<style lang="scss">
.my-settle-container {
  /* 底部固定定位 */
  position: fixed;
  bottom: 0;
  left: 0;
  /* 设置宽高和背景色 */
  width: 100%;
  height: 50px;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 5px;
  font-size: 14px;

  .radio {
    display: flex;
    align-items: center;
  }

  .amount {
    color: #c00000;
  }

  .btn-settle {
    height: 50px;
    min-width: 100px;
    background-color: #c00000;
    color: white;
    line-height: 50px;
    text-align: center;
    padding: 0 10px;
  }
}
</style>
